<?php
namespace Admin\Controller;
class ServerController extends CommonController {

	public function index(){
		if (IS_GET) {
			$data = $this -> api(array('api'=>'index'));
			$this -> show($data['info']['content']);die;
		}elseif (IS_POST) {
			$data = $this -> api(I());
			switch (I('api')) {
				case 'install':
					if ($data['info']['dotype'] == 'mkdata') {
						$this -> install($data['info']['content']);
					}else{
						$this -> ajaxReturn($data['info']);
					}
					break;
				case 'update':
					if ($data['info']['dotype'] == 'mkdata') {
						$this -> update($data['info']['content']);
					}else{
						$this -> ajaxReturn($data['info']);
					}
					break;
				
				default:
					$this -> ajaxReturn($data['info']);
					break;
			}
		}
	}

	// 更新appid等信息
	function setapp(){
		if (IS_POST) {
			$appinfo = array(
				'appid'=>I('appid'),
				'appkey'=>I('appkey'),
				);
			$str = "<?php \n\r//文件由系统自动生成，如非必要请在后台修改！\n\rreturn ".var_export($appinfo,true).';';
			\Think\Storage::put(COMMON_PATH.'Conf/appinfo.php',$str);
			$this -> success('保存成功！');
		}
	}

	// 安装插件
	protected function install($data){
		$data['filestatus'] = 1;
		// 校验文件
		foreach ($data['files'] as $key => $file) {
			// if (I('force') != 1 && !$this -> filesha1($file['filename'],$file['pre_sha1'])) {
			// 	$this -> error($file['filename'].'文件验证失败！可能已经被修改！');
			// }
			if (!$this -> fileWriteable(iconv('UTF-8', 'GBK', $file['filename']))) {
				$this -> error($file['filename'].'不可写！');
			}
		}
		// 替换文件
		foreach ($data['files'] as $key => $file) {
			// 备份文件
			if (\Think\Storage::has(iconv('UTF-8', 'GBK', $file['filename']))) {
				\Think\Storage::put(iconv('UTF-8', 'GBK', './_backup/'.$data['module']['group'].'/'.$data['module']['text'].'/'.$data['pre_version'].$file['filename']),\Think\Storage::read(iconv('UTF-8', 'GBK', $file['filename'])));
			}
			// 更新文件
			if (!\Think\Storage::put(iconv('UTF-8', 'GBK',$file['filename']), \Think\Crypt::decrypt($file['content']))) {
				$this -> error($file['filename'].'写入失败！');
			}
		}
		// 升级数据库
		// if ($data['version']['sqls']) {
		// 	if (false === M() -> execute($data['version']['sqls'],true)) {
		// 		$this -> error($data['version']['sqls'].'语句执行错误！');
		// 	}
		// }
		// 更新数据库中的版本信息
		$_data = array(
			'type' => $data['module']['type'],
			'group' => $data['module']['group'],
			'text' => $data['module']['text'],
			'name' => $data['module']['name'],
			'version' => $data['version']['version'],
			'thumb' => $data['module']['thumb'],
			'description' => $data['module']['description'],
			'update_time' => time(),
			'create_time' => time(),
			'sort' => 1,
			'status' => 1,
			'locked' => 1,
			);
		M('plugs') -> add($_data);
		// 清理缓存
		deldir(RUNTIME_PATH);
		$this -> success('安装成功！');
	}

	// 升级插件
	protected function update($data){
		$data['filestatus'] = 1;
		// 校验文件
		foreach ($data['files'] as $key => $file) {
			// if (I('force') != 1 && !$this -> filesha1($file['filename'],$file['pre_sha1'])) {
			// 	$this -> error($file['filename'].'文件验证失败！可能已经被修改！');
			// }
			if (!$this -> fileWriteable(iconv('UTF-8', 'GBK', $file['filename']))) {
				$this -> error($file['filename'].'不可写！');
			}
		}
		// 替换文件
		foreach ($data['files'] as $key => $file) {
			// 备份文件
			if (\Think\Storage::has(iconv('UTF-8', 'GBK', $file['filename']))) {
				\Think\Storage::put(iconv('UTF-8', 'GBK', './_backup/'.$data['module']['group'].'/'.$data['module']['text'].'/'.$data['pre_version'].$file['filename']),\Think\Storage::read(iconv('UTF-8', 'GBK', $file['filename'])));
			}
			// 更新文件
			if (!\Think\Storage::put(iconv('UTF-8', 'GBK',$file['filename']), \Think\Crypt::decrypt($file['content']))) {
				$this -> error($file['filename'].'写入失败！');
			}
		}
		// 升级数据库
		if ($data['version']['sqls']) {
			if (false === M() -> execute($data['version']['sqls'],true)) {
				$this -> error($data['version']['sqls'].'语句执行错误！');
			}
		}
		// 更新数据库中的版本信息
		$_where = array('name'=>array('eq',$data['module']['name']));
		M('plugs') -> where($_where) -> setField('version',$data['version']['version']);
		// 清理缓存
		deldir(RUNTIME_PATH);
		$this -> success('升级成功！');
	}

	// 卸载插件
	protected function uninstall(){
		
	}

	// 检查老文件的md5值
	protected function filesha1($filename,$sha1){
		return sha1(\Think\Storage::read($filename)) == $sha1;
	}

	// 检查文件的状态是否可写
	protected function fileWriteable($filename){
		if (\Think\Storage::has($filename) && !is_writable($filename)) {
			return false;
		}
		return true;
	}

	// 执行sql语句；
	protected function execsql($sql){
		return M() -> execute($sql,true);
	}

	protected function api($param){
		// 通讯密匙 需要在线申请！
		$appinfo = F('appinfo');
		$appinfo = load_config(COMMON_PATH.'Conf/appinfo.php');
		// $appid = '1234567890';
		// $appkey = '40bd001563085fc35165329ea1ff5c5ecbdbbeef';
		$appid = $appinfo['appid'];
		$appkey = $appinfo['appkey'];

		$plugs = M('Plugs') -> getField('name,version,type,group,text,status,locked',true);

		$param['host'] = I('server.HTTP_HOST');
		$param['version'] = EBCORE_VERSION;
		$param['appkey'] = $appkey;
		$param['plugs'] = $plugs;

		// 发送appid 加上 参数的post序列化再加密的数据给服务器
		$query = array(
			'appid' => $appid,
			'param' => \Think\Crypt::encrypt(serialize($param),$appkey),
			);
		$url = U('Server/Api/ebcore@localhost');
		$data = $this -> curl_get_contents($url,$query);
		$data = json_decode($data,true);
		if ($data['status']) {
			$data['info'] = unserialize(\Think\Crypt::decrypt($data['info'],$appkey));
			return $data;
		}else{
			if (IS_GET) {
				$this -> data = $data['info'];
				$this -> appinfo = $appinfo;
				$this->display('setapp');die;
			}elseif (IS_POST) {
				$this -> ajaxReturn($data['info']);die;
			}
		}
	}

	protected function curl_get_contents($url,$post_data) {
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_URL, $url);            //设置访问的url地址
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);           //设置超时
		curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);   //用户访问代理 User-Agent
		curl_setopt($ch, CURLOPT_REFERER,_REFERER_);        //设置 referer
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);      //跟踪301
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        //返回结果
		if ($post_data) {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		$r = curl_exec($ch);
		if (false === $r) {
			$res = array(
				'status' => false,
				'info' => "cURL Error: " . curl_error($ch),
				);
			return json_encode($res);
		}
		curl_close($ch);
		return $r;
	}
}